﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Entities;

namespace VideoSeller.Business.Models
{
	public class OfflineContentModel : Repository<OfflineContent>
	{
		private readonly OfflineCategorizationModel _offlineCategorizationModel;

		public OfflineContentModel(OfflineCategorizationModel offlineCategorizationModel)
		{
			_offlineCategorizationModel = offlineCategorizationModel;
		}

		public IEnumerable<OfflineContent> GetAll(Guid userId)
		{
			return Table.Where(x => x.UserId == userId);
		}

		public void AddOfflineContent(OfflineContentItem contentItem, Guid userId)
		{
			var item = new OfflineContent
			{
				Title = contentItem.Name,
				Description = contentItem.Description,
				ImageUrl = contentItem.ThumbnailFileUrl,
				VideoUrl = contentItem.VideoFileUrl,
				Size = contentItem.VideoFileSize,
				PlayTime = 0,
				CreatedTime = DateTime.Now,
				UserId = userId
			};

			if (contentItem.Categories.Count > 0)
			{
				foreach (var category in contentItem.Categories)
				{
					item.OfflineCategorizations.Add(new OfflineCategorization {CategoryId = int.Parse(category)});
				}
			}

			Insert(item);
		}

		public void DeleteContent(int id)
		{
			var content = Table.SingleOrDefault(x => x.Id == id);

			if (content != null)
			{
				_offlineCategorizationModel.DeleteAll(content.OfflineCategorizations);
				Delete(content);
			}
		}
	}
}